package dao

import (
	"encoding/json"
	"fmt"
	"go_src/common"
	"go_src/common/exception"
	"time"
)

type Category struct {
	Count       int    `db:"count" json:"count"`
	Pid         uint64 `db:"pid" json:"pid"`
	Id          uint64 `db:"id" json:"id"`
	CreateAt    int64  `db:"create_at" json:"create_at"`
	UpdateAt    int64  `db:"update_at" json:"update_at"`
	TableName   string
	Slug        string      `db:"slug" json:"slug"`
	Name        string      `db:"name" json:"name"`
	Description string      `db:"description" json:"description"`
	Extends     string      `db:"extends"`
	ExtendMaps  interface{} `json:"extends"`
}

type CategoryDAO interface {
	SaveCategory() common.Result

	SelectCategories() common.Result

	SelectCategoryById() common.Result

	UpdateCategoryById() common.Result

	DeleteCategoryById() common.Result

	BatchDeleteCategoriesByIds(ids []string) common.Result

	IncreaseArticleCountByName() common.Result
}


func (category *Category) MarshalJSON() ([]byte, error) {
	json.Unmarshal([]byte(category.Extends), &category.ExtendMaps)
	return json.Marshal(*category)
}

/**
func (category *Category) UnmarshalJSON(data []byte) error {
	fmt.Println("okkk")
	type TempCategory Category
	c := struct {
		Extends string `json:"extends"`
		*TempCategory
	}{
		Extends:      common.ToJson(category.Extends),
		TempCategory: (*TempCategory)(category),
	}

	if err := json.Unmarshal(data, &c); err != nil {
		fmt.Println(err)
		return err
	}
	if err := json.Unmarshal([]byte(c.Extends), &category.Extends); err != nil {
		return err
	}
	return nil
}
**/
func (category *Category) SelectCategories(pagination *common.Pagination) common.Result {

	var categories []Category
	err := Db.Select(&categories, "select * from category")
	pagination.Total = uint64(len(categories))
	pagination.CurrentPage = 1
	pagination.TotalPage = 1
	pagination.PerPage = int(pagination.Total)+100
	if err != nil {
		return common.Result{Success: false, Error: exception.BusinessError{Code: exception.DbOperatorExceptionCode,
			Message: "数据库错误", OriginalError: err}}
	}
	fmt.Println(categories)
	return common.Result{Success: true, Data: categories}
}

func (category *Category) SaveCategory() common.Result {
	category.Extends = common.ToJson(category.ExtendMaps)
	insertSqlResult := getInsertSql(*category)
	if !insertSqlResult.Success {
		return insertSqlResult
	}

	return executeChangeSql(insertSqlResult.Data.(string))
}

func NewCategory() *Category {
	c := new(Category)
	c.UpdateAt = time.Now().UnixNano() / 1e6
	c.CreateAt = c.UpdateAt
	c.TableName = "category"
	return c
}
